Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,

Given 1->4->3->2->5->2 and x = 3,

return 1->2->2->4->3->5.

Solution:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode partition(ListNode head, int x) {
  11. if (head == null) {
  12. return null;
  13. }
  14. // create fake heads
  15. ListNode f1 = new ListNode(0);
  16. ListNode f2 = new ListNode(0);
  17. ListNode p1 = f1;
  18. ListNode p2 = f2;
  19. ListNode node = head;
  20. while (node != null) {
  21. if (node.val < x) {
  22. p1.next = node;
  23. p1 = p1.next;
  24. } else {
  25. p2.next = node;
  26. p2 = p2.next;
  27. }
  28. node = node.next;
  29. }
  30. p1.next = f2.next;
  31. p2.next = null;
  32. return f1.next;
  33. }
  34. }